//
//  XXDownFileToFoler.m
//  downFileTest
//
//  Created by 拼凑的断音 on 16/6/23.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "XXDownFileToFoler.h"

@implementation XMLXXDownFileModel

+(XMLXXDownFileModel*)newXXDownFileModelWithUrl:(NSString *)url saveName:(NSString *)name saveType:(FileToFolerType)type
{
    XMLXXDownFileModel *temp =[[XMLXXDownFileModel alloc] init];
    temp.url = url;
    temp.saveName = name;
    temp.type = type;
    temp.count = 0;
    temp.total = 0;
    return temp;
}

@end

@interface XXDownFileToFoler ()<NSURLSessionDownloadDelegate>

@property (strong,nonatomic) NSURLSession *session;

@property (strong,nonatomic) NSMutableArray <XMLXXDownFileModel*> *taskArray;

@property (nonatomic,copy) XXDownProgressBlock pBlock;

@property (nonatomic,copy) XXDownFileCompleteBlock cBlock;

@property (nonatomic,strong) NSMutableArray <NSURLSessionDownloadTask*> *downTaskArray;

@end

@implementation XXDownFileToFoler
#pragma mark getter

+(instancetype)shareInstance
{
    static XXDownFileToFoler *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

+(void)downFileWithUrlArray:(NSMutableArray<XMLXXDownFileModel *> *)urlArray
          downProgressBlock:(XXDownProgressBlock)progressBlock
              completeBlock:(XXDownFileCompleteBlock)completeBlock
{
    [[XXDownFileToFoler shareInstance] downFileWithUrlArray:urlArray
                                          downProgressBlock:progressBlock
                                              completeBlock:completeBlock];
}


+(void)stopDownFile
{
    [[self shareInstance] stopDownFile];
}

-(void)downFileWithUrlArray:(NSMutableArray<XMLXXDownFileModel *> *)urlArray
          downProgressBlock:(XXDownProgressBlock)progressBlock
              completeBlock:(XXDownFileCompleteBlock)completeBlock
{
    _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                             delegate:self
                                        delegateQueue:nil];
    self.taskArray = urlArray;
    self.pBlock = progressBlock;
    self.cBlock = completeBlock;
    [self pushResquest];
}



-(void)pushResquest
{
    self.downTaskArray = [NSMutableArray array];
    for (int i=0; i<self.taskArray.count; i++)
    {
        XMLXXDownFileModel *temp = self.taskArray[i];
        NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:temp.url]];
        NSURLSessionDownloadTask *task = [_session downloadTaskWithRequest:request];
        [task resume];
        [self.downTaskArray addObject:task];
    }
}

-(void)stopDownFile
{
    for (NSURLSessionDownloadTask* task in self.downTaskArray)
    {
        [task cancel];
    }
}


#pragma mark NSURLSessionDownloadDelegate
-(void)URLSession:(NSURLSession *)session
     downloadTask:(NSURLSessionDownloadTask *)downloadTask
     didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        XMLXXDownFileModel *temp = self.taskArray[downloadTask.taskIdentifier-1];
        temp.count = totalBytesWritten;
        temp.total = totalBytesExpectedToWrite;
        double rate = 0;
        for (int i=0; i<self.taskArray.count; i++)
        {
            XMLXXDownFileModel *temp = self.taskArray[i];
            if (temp.total==0)
            {
                continue;
            }
            rate += (temp.count*1.0/temp.total/self.taskArray.count);
        }
        NSLog(@"%f",rate);
        dispatch_async(dispatch_get_main_queue(), ^{
            self.pBlock(rate);
        });
    });
}

//下载失败
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if([error.localizedDescription isEqualToString:@"cancelled"])
    {
        XMLXXDownFileModel *temp = self.taskArray[task.taskIdentifier-1];
        NSFileManager *fileManager = [NSFileManager defaultManager];//文件管理
        NSURL *documentsDirectory=[NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]];
        NSURL *destinationPath = [documentsDirectory URLByAppendingPathComponent:temp.saveName];
        [fileManager removeItemAtURL:destinationPath error:NULL];//确保文件不在
    }
}

//下载成功
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    XMLXXDownFileModel *temp = self.taskArray[downloadTask.taskIdentifier-1];
    NSFileManager *fileManager = [NSFileManager defaultManager];//文件管理
    NSURL *documentsDirectory=[NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]];
    NSURL *destinationPath = [documentsDirectory URLByAppendingPathComponent:temp.saveName];
    NSError *error;
    [fileManager removeItemAtURL:destinationPath error:NULL];//确保文件不在
    BOOL success = [fileManager copyItemAtURL:location toURL:destinationPath error:&error];
    if(success)
    {
        NSLog(@"success path:%@",destinationPath);
    }
    else
    {
        NSLog(@"error:%@",error);
    }
    
    BOOL isAllOk = YES;
    for (int i=0; i<self.taskArray.count; i++)
    {
        XMLXXDownFileModel *temp = self.taskArray[i];
        if (temp.total!=temp.count)
        {
            isAllOk = NO;
            break;
        }
    }
    if (isAllOk)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.cBlock(YES);
        });
    }
}


@end
